﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO.Ports;
using System.Windows;
using System.Threading;

namespace PluginManager
{
    public class SerialPortScan : IScan
    {
        private string portName;
        private int baduRate;
        public SerialPortScan(string portName, int baduRate)
        {
            this.portName = portName;
            this.baduRate = baduRate;
        }
        private SerialPort sp = new SerialPort();
        public void Initial()
        {
            sp.PortName = this.portName;
            sp.BaudRate = this.baduRate;
            sp.Parity = Parity.None;
            sp.StopBits = StopBits.One;
            sp.DataReceived += new SerialDataReceivedEventHandler(sp_DataReceived);
            sp.ReceivedBytesThreshold = 1;
            try
            {
                sp.Open();
            }
            catch (Exception ex)
            {
                MessageBox.Show("端口" + this.portName + "打开失败！");
                sp.DataReceived -= new SerialDataReceivedEventHandler(sp_DataReceived);
            }

        }

        void sp_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            sp.DataReceived -= new SerialDataReceivedEventHandler(sp_DataReceived);
            byte[] readBuffer = new byte[sp.ReadBufferSize];
            sp.Read(readBuffer, 0, readBuffer.Length);

            Thread.Sleep(500);

            string sn = Encoding.ASCII.GetString(readBuffer);

            if (OnDataReceived != null) OnDataReceived.Invoke(sn);

            sp.DataReceived += new SerialDataReceivedEventHandler(sp_DataReceived);
        }


        public event Action<string> OnDataReceived;


        public void Close()
        {
            if (sp.IsOpen) sp.Close();
        }
    }


    public class RFIDScan : IScan
    {
        public void Initial()
        {
            throw new NotImplementedException();
        }


        public event Action<string> OnDataReceived;


        public void Close()
        {
            throw new NotImplementedException();
        }
    }


}
